package com.logistics.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.logistics.compont.ResponseApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AliPayController {

    @Autowired
    AlipayClient alipayClient;

    @GetMapping("/createNative")
    public Map createNative(String order_num, String total_fee) {

        Map<String, String> map = new HashMap<String, String>();
        //创建预下单请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        //转换下单金额按照元
        long total = Long.parseLong(total_fee);
        BigDecimal bigTotal = BigDecimal.valueOf(total);
        //转换率
        BigDecimal cs = BigDecimal.valueOf(100d);
        //将分转换为元
        BigDecimal bigYuan = bigTotal.divide(cs);

        System.out.println("预下单金额:" + bigYuan.doubleValue());

        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + order_num + "\"," +
                "    \"total_amount\":\"" + bigYuan.doubleValue() + "\"," +
                "    \"subject\":\"测试购买商品001\"," +
                "    \"store_id\":\"xa_001\"," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数

        //发出预下单业务请求
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);

            //从相应对象读取相应结果 10000表示成功
            String code = response.getCode();
            System.out.println("响应码:" + code);

            //全部的响应结果
            String body = response.getBody();
            System.out.println("返回结果:" + body);

            if (code.equals("10000")) {
                //支付二维码
                map.put("qrcode", response.getQrCode());
                //交易流水号
                map.put("out_trade_no", response.getOutTradeNo());
                //支付金额
                map.put("total_fee", total_fee);

                System.out.println("qrcode:" + response.getQrCode());
                System.out.println("out_trade_no:" + response.getOutTradeNo());
                System.out.println("total_fee:" + total_fee);
            } else {
                System.out.println("预下单接口调用失败:" + body);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/queryPayStatus")
    public ResponseApi queryPayStatus(String out_trade_no) {

        //计数器
        int x = 0;

        ResponseApi result = null;
        while (true) {
            //调用查询接口
            Map<String, String> map = null;

            try {
                map = queryPayStatus2(out_trade_no);
            } catch (Exception e1) {
                /*e1.printStackTrace();*/
                System.out.println("调用查询服务出错");
            }

            if (map == null) {//出错
                result =  ResponseApi.FAILED("支付出错" + map.get("tradestatus"));
            }

            if (map.get("tradestatus") != null && map.get("tradestatus").equals("TRADE_SUCCESS")) {//如果成功
                result = ResponseApi.SUCCESS("支付成功");

                //修改订单状态
//                orderService.updateOrderStatus(out_trade_no, map.get("trade_no"));

                break;
            }

            if (map.get("tradestatus") != null && map.get("tradestatus").equals("TRADE_CLOSED")) {//如果成功
                result = ResponseApi.SUCCESS("未付款交易超时关闭，或支付完成后全额退款");
                break;
            }

            if (map.get("tradestatus") != null && map.get("tradestatus").equals("TRADE_FINISHED")) {//如果成功
                result = ResponseApi.SUCCESS( "交易结束，不可退款");
                break;
            }

            try {
                Thread.sleep(3000);//间隔三秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //为了不让循环无休止地运行，我们定义一个循环变量，如果这个变量超过了这个值则退出循环，设置时间为5分钟
            x++;
            if (x >= 100) {
                result = ResponseApi.FAILED("二维码超时");
                break;
            }

        }


        return result;
    }

    public Map<String, String> queryPayStatus2(String out_trade_no) {
        Map<String, String> map = new HashMap<String, String>();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + out_trade_no + "\"," +
                "    \"trade_no\":\"\"}"); //设置业务参数
        //发出请求
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            String code = response.getCode();
            System.out.println("返回值1:" + response.getBody());
            if (code.equals("10000")) {
                //System.out.println("返回值2:"+response.getBody());
                map.put("out_trade_no", out_trade_no);
                map.put("tradestatus", response.getTradeStatus());
                map.put("trade_no", response.getTradeNo());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }

}
